package site.leiwa._01_单例模式;


import site.leiwa.common.Safe;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;

/**
 * Description 单例扩展（生成固定N个）随机调用一个
**/

@Safe
public class _03Singleton {


    // 定义最多能生成的实例个数
    private static final int maxNumOfSingleton = 2;

    // 每个实例化对象的名字
    private static final ArrayList<String> names = new ArrayList<>();

    // 存储实例化后的对象
    private static final ArrayList<_03Singleton> singletonArrayList = new ArrayList<>();

    // 当代实例化的序号
    private static int initNum = 0;

    public static int getInitNum() {
        return initNum;
    }

    // 产生所有的对象
    static {
        for (int i = 0; i < maxNumOfSingleton; i++) {
            singletonArrayList.add(new _03Singleton("第" + i + "个实例化对象"));
        }
    }

    private _03Singleton(String name){

    }

    // 随机获取一个实例化对象
    public static _03Singleton getInstance(){
        initNum = ThreadLocalRandom.current().nextInt(maxNumOfSingleton);
        return singletonArrayList.get(initNum);
    }





    // 验证是否安全
    public static void main(String[] args) throws InterruptedException {
        ArrayList<String> list = new ArrayList<>(200);
        ArrayList<Thread> threads = new ArrayList<>(200);
        for (int i = 0; i < 100; i++) {
            Thread t = new Thread(() -> {
                try {
                    Thread.sleep(1500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                list.add(_03Singleton.getInstance().toString());
            });
            threads.add(t);
        }
        threads.forEach(Thread::start);
        Thread.sleep(2500);
        Set<String> set = new HashSet<>();
        boolean b = set.addAll(list);
        System.out.println(set.size());
    }
}